package com.pig.config;

import com.pig.dao.UserDao;
import com.pig.pojo.user.User;

import com.pig.util.UserThreadLocal;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;

@Component
public class ShiroUserRealm extends AuthorizingRealm {


    @Autowired
    private UserDao userDao;

//   @Autowired
//   private UserMapper userMapper;



    /*
     * 负责认证信息的获取和封装认证*/
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(
            AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取登录用户信息（用户名，密码
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        //基于用户名查询数据库中的用户对象
//        QueryWrapper queryWrapper=new QueryWrapper();
//        queryWrapper.eq("username",username);
//        User user = use.selectOne(queryWrapper);
        User user = userDao.findUserByUserName(username);
        System.out.println("ShiroUserRealm >>> " + user);


        UserThreadLocal.set(user);
        //检测用户是否存在
        if (user == null)
            throw new UnknownAccountException();


        //检测用户是否被禁用
//        if (user.getValid==0)
//            throw new LockedAccountException();

        //封装用户信息并返回
//        ByteSource byteSource = ByteSource.Util.bytes(user.getSalt());

        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
                user,//用户身份
                user.getPassword(),//凭证-已加密
//                byteSource,//凭证盐
                getName());

        return info;
    }

    //设置加密匹配器
//    @Override
//    public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
//        HashedCredentialsMatcher cmatcher = new HashedCredentialsMatcher();
//        cmatcher.setHashAlgorithmName("MD5");
//        cmatcher.setHashIterations(1);
//        super.setCredentialsMatcher(cmatcher);
//    }


    @Override
    public CredentialsMatcher getCredentialsMatcher() {
        HashedCredentialsMatcher cmatcher = new HashedCredentialsMatcher();
        cmatcher.setHashAlgorithmName("MD5");
        cmatcher.setHashIterations(1);
        return cmatcher;
    }



    /*
     * 负责授权信息的获取和封装*/
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }
}
